package com.huawei.esdk.oa.device.ad;

import java.util.ArrayList;
import java.util.List;
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.SearchCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.Response;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
import org.apache.directory.api.ldap.model.message.SearchResultEntry;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.log4j.Logger;
import com.huawei.esdk.oa.device.ad.common.LdapConnectionFactory;
import com.huawei.esdk.platform.common.SDKResult;
import com.huawei.esdk.platform.common.config.ConfigManager;
import com.huawei.esdk.platform.common.constants.ESDKErrorCodeConstant;
import com.huawei.esdk.tp.common.ErrInfo;
import com.huawei.esdk.tp.cxf.enumgen.SiteType;
import com.huawei.esdk.tp.device.oa.IADCapability;
import com.huawei.esdk.tp.domain.model.Site;

public class ADCapability implements IADCapability
{
    
    private String siteUriMappingStr = ConfigManager.getInstance().getValue("tpoa_ad_mail");
    
    private static final Logger LOGGER = Logger.getLogger(ADCapability.class);
    
    @Override
    public SDKResult<List<Site>> queryExchangeSites()
    {
        
        SDKResult<List<Site>> result = new SDKResult<List<Site>>();
        
        LdapConnection ldapConnection;
        try
        {
            ldapConnection = LdapConnectionFactory.getConnection();
        }
        catch (Exception e)
        {
            LOGGER.error("AD DEVICE CONN ERROR");
            result.setErrCode(ESDKErrorCodeConstant.ERROR_CODE_DEVICE_CONN_ERROR);
            return result;
        }
        
        List<Site> sites = new ArrayList<Site>();
        
        SearchRequest req = new SearchRequestImpl();
        req.setScope(SearchScope.SUBTREE);
        
        req.setTimeLimit(0);
        
        try
        {
            req.setBase(new Dn(LdapConnectionFactory.getDC(LdapConnectionFactory.domain)));
            req.addAttributes(siteUriMappingStr);
            req.setFilter(ConfigManager.getInstance().getValue("tpoa_ad_msExchResourceMetaData_Room"));
            
            SearchCursor searchCursor = ldapConnection.search(req);
            
            while (searchCursor.next())
            {
                Response response = searchCursor.get();
                
                if (response instanceof SearchResultEntry)
                {
                    Entry resultEntry = ((SearchResultEntry)response).getEntry();
                    
                    String mailAddress = resultEntry.get(siteUriMappingStr).getString();
                    
                    Site site = new Site();
                    site.setUri(mailAddress);
                    sites.add(site);
                    
                }
            }
            
            searchCursor.close();
        }
        catch (LdapException e)
        {
            result.setErrCode(ErrInfo.SDK_SYSTEM_ERRORCODE);
            LOGGER.error("AD queryExchangeSites method error ", e);
        }
        catch (CursorException e)
        {
            result.setErrCode(ErrInfo.SDK_SYSTEM_ERRORCODE);
            LOGGER.error("AD queryExchangeSites method error ", e);
        }
        
        result.setErrCode(0);
        result.setResult(sites);
        
        return result;
    }
    
    @Override
    public SDKResult<List<Site>> queryExchangeSitesByUser(List<String> userAddress)
    {
        SDKResult<List<Site>> result = new SDKResult<List<Site>>();
        
        LdapConnection ldapConnection;
        try
        {
            ldapConnection = LdapConnectionFactory.getConnection();
        }
        catch (Exception e1)
        {
            LOGGER.error("AD DEVICE CONN ERROR");
            result.setErrCode(ESDKErrorCodeConstant.ERROR_CODE_DEVICE_CONN_ERROR);
            return result;
        }
        
        List<Site> sites = new ArrayList<Site>();
        
        SearchRequest req = new SearchRequestImpl();
        req.setScope(SearchScope.SUBTREE);
        
        req.setTimeLimit(0);
        
        try
        {
            req.setBase(new Dn(LdapConnectionFactory.getDC(LdapConnectionFactory.domain)));
            req.addAttributes("msRTCSIP-PrimaryUserAddress");
            req.addAttributes("displayName");
            req.addAttributes("extensionAttribute1");
            req.addAttributes("extensionAttribute2");
            req.addAttributes("extensionAttribute3");
            req.addAttributes("extensionAttribute4");
            
            for (String addr : userAddress)
            {
                req.setFilter("(&(msExchResourceMetaData=ResourceType:Room)(mail=" + addr
                    + ")(extensionAttribute1=VideoRoom))");
                SearchCursor searchCursor2 = ldapConnection.search(req);
                if (searchCursor2.next())
                {
                    Response response = searchCursor2.get();
                    
                    if (response instanceof SearchResultEntry)
                    {
                        Entry resultEntry = ((SearchResultEntry)response).getEntry();
                        
                        Site site = new Site();
                        site.setUri(resultEntry.get("extensionAttribute2").getString());
                        site.setSiteType(resultEntry.get("extensionAttribute4").getString());
                        site.setName(resultEntry.get("extensionAttribute3").getString());
                        sites.add(site);
                    }
                }
                searchCursor2.close();
                
                req.setFilter("(&(msRTCSIP-UserEnabled=TRUE)(msRTCSIP-PrimaryUserAddress=" + "sip:" + addr + "))");
                SearchCursor searchCursor1 = ldapConnection.search(req);
                if (searchCursor1.next())
                {
                    Response response = searchCursor1.get();
                    
                    if (response instanceof SearchResultEntry)
                    {
                        Entry resultEntry = ((SearchResultEntry)response).getEntry();
                        
                        Site site = new Site();
                        site.setUri(resultEntry.get("msRTCSIP-PrimaryUserAddress").getString());
                        site.setSiteType(SiteType.SITE_TYPE_SIP.toString());
                        site.setName(resultEntry.get("displayName").getString());
                        sites.add(site);
                    }
                }
                searchCursor1.close();
            }
        }
        catch (LdapException e)
        {
            LOGGER.error("AD queryExchangeSites method error ", e);
            result.setErrCode(ESDKErrorCodeConstant.ERROR_CODE_DEVICE_CONN_ERROR);
            result.setDescription("AD DEVICE CONN ERROR");
            return result;
        }
        catch (CursorException e)
        {
            LOGGER.error("AD queryExchangeSites method error ", e);
            result.setErrCode(ESDKErrorCodeConstant.ERROR_CODE_DEVICE_CONN_ERROR);
            result.setDescription("AD DEVICE CONN ERROR");
            return result;
        }
        
        result.setErrCode(0);
        result.setResult(sites);
        
        return result;
    }
    
}
